package com.samphanie.security.validation.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.samphanie.common.utils.MyRequestWrapper;
import com.samphanie.security.validation.ValidateCodeProcessorHolder;
import com.samphanie.security.validation.enums.ValidateCodeType;
import com.samphanie.security.validation.exception.ValidateCodeException;
import com.samphanie.security.validation.properties.ValidateProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
@RequiredArgsConstructor
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    private final ValidateProperties validateProperties;
    /**
     * 验证码校验失败处理器
     */
    private final CodeAuthenticationFailureHandler onAuthenticationFailure;
    /**
     * 系统中的校验码处理器
     */
    private final ValidateCodeProcessorHolder validateCodeProcessorHolder;
    /**
     * 存放所有需要校验验证码的url
     */
    private final Map<String, ValidateCodeType> urlMap = new HashMap<>();
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        addUrlToMap(validateProperties.getKaptcha().getUrls(), ValidateCodeType.IMAGE);
        addUrlToMap(validateProperties.getSms().getUrls(), ValidateCodeType.SMS);
    }

    /**
     * 将系统中配置的需要校验验证码的URL根据校验的类型放入map
     */
    protected void addUrlToMap(List<String> urls, ValidateCodeType type) {
        if (CollUtil.isNotEmpty(urls)) {
            urls.forEach(e -> urlMap.put(e, type));
        }
    }

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws ServletException, IOException {

        if (!request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            ValidateCodeType type = getValidateCodeType(request);
            MyRequestWrapper requestWrapper = new MyRequestWrapper(request);
            if (type != null) {
                log.info("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
                try {
                    validateCodeProcessorHolder.findValidateCodeProcessor(type)
                            .validate(new ServletWebRequest(request, response), requestWrapper);
                    log.info("验证码校验通过");
                } catch (ValidateCodeException e) {
                    onAuthenticationFailure.onAuthenticationFailure(request, response, e);
                    return;
                }
            }

            chain.doFilter(requestWrapper, response);
        }

    }

    /**
     * 获取校验码的类型，如果当前请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        ValidateCodeType result = null;
        if (!StrUtil.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}
